package com.cloud.project.web;

import java.util.List;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cloud.bug.service.BugStatService;
import com.cloud.platform.DateUtil;
import com.cloud.project.model.Project;
import com.cloud.project.service.ProjectService;

@Controller
@RequestMapping("project")
public class ProjectBean {

	@Autowired
	private ProjectService projectService;
	
	@Autowired
	private BugStatService bugStatService;
	
	/**
	 * open project
	 * 
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/openProject.do")
	public ModelAndView openProject(@RequestParam("projectId") String projectId) {
		
		ModelAndView mv = new ModelAndView("project/projectLook");
		
		try {
			// get bug info
			Project project = projectService.getProject(projectId);
			
			// get bug status statistic info
			JSONArray statusStat = bugStatService.statBugStatus(projectId, false);
			
			// get person recive bug statistic info
			JSONArray personReciveStat = bugStatService.statPersonRecive(projectId);
			
			// get person solve bug statistic info
			JSONArray personSolveStat = bugStatService.statPersonSolve(projectId);
			
			// init model and view
			mv.addObject("project", project);
			mv.addObject("statusStat", statusStat);
			mv.addObject("personReciveStat", personReciveStat);
			mv.addObject("personSolveStat", personSolveStat);
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return mv;
	}
	
	/**
	 * get projects
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getProjects.do")
	public String getProjects() {
		
		// get projects
		List<Project> projects = projectService.searchProjects(null);
		
		// convert to json format
		JSONArray pjtsArr = JSONArray.fromObject(projects);
		
		return pjtsArr.toString();
	}
	
	/**
	 * save project 
	 * 
	 * @param project
	 * @return
	 */
	@RequestMapping("/saveProject.do")
	public String saveProject(Project project,
			@RequestParam("start") String startDate, @RequestParam("end") String endDate) {
		
		try {
			project.setStartDate(DateUtil.parseDate(startDate));
			project.setEndDate(DateUtil.parseDate(endDate));
			
			projectService.saveProject(project);
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return "project/project";
	}
}
